package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.utils.common.AppThreadLocalUtil;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private IWemediaClient iWemediaClient;

    @Autowired
    private CacheService cacheService;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //1. 查询所有的文章数据
        //1.1 获取前面5天的时间
        Date date = DateTime.now().minusDays(5).toDate();
        //1.2 查询前面5天的文章数据
        List<ApArticle> list = apArticleMapper.findArticleListByDays(date);

        //2. 计算所有文章的得分
        if(null != list && list.size() > 0){
            List<HotArticleVo> voList = computeHotArticleScore(list);

            //3. 把数据缓存到redis
            cacheTagToRedis(voList);
        }
    }

    /**
     * 缓存数据到每一个频道和推荐
     * @param voList
     */
    private void cacheTagToRedis(List<HotArticleVo> voList) {
        //1. 缓存每个频道的数据
        //1.1 查询所有的频道
        ResponseResult responseResult = iWemediaClient.findAll();
        if(null != responseResult && responseResult.getCode() == 200){
            if(null != responseResult.getData()){
                //1.2 遍历所有的频道并查询当前遍历频道的所有的文章->排序 -> 获取得分最高的30行记录
                String json = JSON.toJSONString(responseResult.getData());
                List<WmChannel> channelList = JSON.parseArray(json, WmChannel.class);

                for (WmChannel channel : channelList) { //遍历一个频道出来
                    List<HotArticleVo> list = voList.stream()
                            .filter(item -> channel.getId().equals(item.getChannelId()))
                            .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                            .limit(30)
                            .collect(Collectors.toList());

                    //1.3 把获取的30行记录存储到redis里面-key: 前缀+频道id,value: json(30行记录)
                    cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + channel.getId() , JSON.toJSONString(list));
                }
            }
        }

        // 添加推荐的数据
        List<HotArticleVo> list = voList.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG, JSON.toJSONString(list));

    }

    //计算所有文章的得分
    private List<HotArticleVo> computeHotArticleScore(List<ApArticle> list) {
        List<HotArticleVo> voList = new ArrayList<>(list.size());

        for (ApArticle article : list) {
            HotArticleVo vo = new HotArticleVo();
            BeanUtils.copyProperties(article, vo);

            vo.setScore(computeScore(article));
            voList.add(vo);
        }

        return voList;
    }

    /**
     * 计算一篇文章的得分
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;

        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }

        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }

        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }

        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
